package 刷题.leedcode22;
//快慢指针法
//1 2 3 4 5 6 7 8 9
//倒数第一个元素 k = 1
//pre = head.cur = head
//cur先走k步，然后pre和cur一起走，当cur = null时，pre指向该节点
public class Solution2 {
    public ListNode FindKthToTail(ListNode head,int k){
        if(head == null){
            return head;
        }
        int size = 0;
        while(head != null){
            ++size;
            head = head.next;
        }
        if(k < 1 || k > size){
            throw new RuntimeException("空指针异常");
        }
        ListNode preNode = head;
        ListNode curNode = head;
        while(k != 0){
            curNode = curNode.next;
            k--;
        }
        while(curNode != null){
            preNode = preNode.next;
            curNode = curNode.next;
        }
        return preNode;
    }
}
